package online.zhangwenzhe.common.token;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.data.redis.connection.RedisConnection;
import org.springframework.data.redis.core.RedisCallback;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.HttpMethod;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class TokenInterceptor implements HandlerInterceptor {
    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    @Override
    public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) throws Exception {
        //防止重复提交仅对post,put,delete生效
        if (!"POST".equals(httpServletRequest.getMethod()) &&
                !"PUT".equals(httpServletRequest.getMethod()) &&
                !"DELETE".equals(httpServletRequest.getMethod())) {
            return true;
        }

        String token = httpServletRequest.getHeader("token");
        if (StringUtils.isEmpty(token)) {
            return false;
        }

        //为了解决事务问题用del方法判断是不是第一次查询
        //多个请求del时，肯定只有一个成功，也就是结果>0
        //先get再del的方法可能会有多个请求get成功,需要事务保证
        Boolean isValid = redisTemplate.execute(new RedisCallback<Boolean>() {
            @Override
            public Boolean doInRedis(RedisConnection connection) throws DataAccessException {
                long result = 0;
                result = connection.del(token.getBytes());
                return result > 0;
            }
        });
        return isValid;
    }

    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {

    }
}
